#include "ModelImporter.h"
#include "ModelImporterDialog.h"

#include <MMM/XMLTools.h>
#include <MMM/Model/ModelReaderXML.h>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>

using namespace MMM;

ModelImporter::ModelImporter(QWidget* widget) :
    MotionHandler(MotionHandlerType::IMPORT, "Import model file as motion"),
    widget(widget)
{
}

std::string ModelImporter::getName() {
    return NAME;
}

void ModelImporter::handleMotion(MotionList motions) {
    QSettings settings;
    std::string modelFilePath = QFileDialog::getOpenFileName(widget, QString::fromStdString(getDescription()), settings.value("model/searchpath", "").toString(), QString::fromStdString("model files (*.xml)")).toStdString();
    if (!modelFilePath.empty()) {
        settings.setValue("model/searchpath", QString::fromStdString(XML::getPath(modelFilePath)));
        MMM::ModelReaderXMLPtr modelReader(new MMM::ModelReaderXML());
        MMM::ModelPtr model = modelReader->loadModel(modelFilePath);
        if (!model) {
            QMessageBox* msgBox = new QMessageBox(widget);
            msgBox->setText(QString::fromStdString("Could not load model from " + modelFilePath));
            msgBox->exec();
        } else {
            ModelImporterDialog* dialog = new ModelImporterDialog(model, widget);
            settings.setValue("motion/path", QString::fromStdString(modelFilePath));
            settings.setValue("motion/type", QString::fromStdString("ModelAsMotion"));
            emit openMotions(dialog->getMotions());
        }
    }
}
